const await = require("await-stream-ready/lib/await");

const Service = require("egg").Service;

class PermissionService extends Service {
  // 获取菜单列表
  async getPermissionList() {
    const {
      app
    } = this;
    try {
      return await app.model.Permission.findAll({
        where: {
          delFlag: 0
        },
        attributes: ["id", "name", "path", "component", "title", "sort"],
      });
    } catch (err) {
      throw new Error(err)
    }
  }

  async getSelfPermissionList(userId) {
    const {
      app,
      ctx
    } = this;
    const {
      accountNumber
    } = ctx.decode;
    try {
      if (accountNumber == 'admin') {
        return this.getPermissionList()
      } else {
        let userRoles = await app.model.UserRole.findAll({
          where: {
            userId: userId
          },
        })
        let roles = userRoles.map(userRole => {
          return userRole.roleId
        })
        let selfRoles = await app.model.Role.findAll({
          where: {
            id: roles
          },
          include: [{
            model: app.model.Permission,
          }],
        });
        let permissionList = [];
        let ids = []
        selfRoles.forEach(role => {
          if (role.permissions.length > 0) {
            role.permissions.forEach(permission => {
              if (!ids.includes(permission.id)) {
                permissionList.push(permission);
                ids.push(permission.id)
              }
            });
          }
        });

        return permissionList
      }
    } catch (err) {
      throw new Error(err)
    }

  }

  /**
   * 添加修改菜单
   * @param {*} param0 
   * @returns 
   */
  async modifyPermission({
    id,
    name,
    path,
    component,
    title,
    sort
  }) {
    const {
      app
    } = this;
    try {
      if (!id) {
        return await app.model.Permission.create({
          name,
          path,
          component,
          title,
          sort
        });
      } else {
        const exit = await app.model.Permission.findByPk(id);
        if (!exit) {
          this.ctx.logger.debug(`根据${id}无法查询到模板`);
          throw new Error("无法查询到模板");
        }
        exit.update({
          name,
          path,
          component,
          title,
          sort
        });
        return true;
      }
    } catch (err) {
      console.log(err);
      throw new Error(err)
    }
  }


  /**
   * 删除菜单
   * @param {*} id 
   * @returns 
   */
  async deletePermission(id) {
    const {
      app,
      ctx
    } = this;
    let transaction = null;
    try {

      transaction = await ctx.model.transaction();
      await app.model.Permission.update({
        delFlag: 1,
      }, {
        where: {
          id,
        },
        transaction,
      });

      /**
       *
       * 批量删除
       */
      await app.model.RolePermission.destroy({
        where: {
          permissionId: id,
        },
        transaction
      });
      await transaction.commit();
      return true;
    } catch (err) {
      await transaction.rollback();
      throw new Error(err);
    }
  }

}

module.exports = PermissionService;